package com.cd.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.cd.model.User;
import com.cd.util.CheckRegister;
import com.cd.util.DBUtil;
import com.cd.util.RE;
import com.cd.util.ReturnResult;

public class RegisterServlet extends HttpServlet
{

	/**
	 * Constructor of the object.
	 */
	public RegisterServlet()
	{
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy()
	{
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		doPost(request, response);
		/*
		 * response.setContentType("text/html"); PrintWriter out =
		 * response.getWriter(); out.println(
		 * "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		 * out.println("<HTML>");
		 * out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		 * out.println("  <BODY>"); out.print("    This is ");
		 * out.print(this.getClass()); out.println(", using the GET method");
		 * out.println("  </BODY>"); out.println("</HTML>"); out.flush();
		 * out.close();
		 */
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		request.setCharacterEncoding("UTF-8");
		User user = new User();
		/**
		 * 检验正则
		 */
		RE regular = new RE();
		DBUtil dataBase = new DBUtil();
		StringBuffer result = new StringBuffer();
		ResultSet rs = null;
		HttpSession session = request.getSession();
		String username = "";
		String password = "";
		String repassword = "";
		String nickname = "";
		String email = "";
		String number = "";
		String sex = "未知";
		int check = 1;
		if (request.getParameter("username") != null)
		{
			username = request.getParameter("username");
		}
		if (request.getParameter("password") != null)
		{
			password = request.getParameter("password");
		}
		if (request.getParameter("repassword") != null)
		{
			repassword = request.getParameter("repassword");
		}
		if (request.getParameter("nickname") != null)
		{
			nickname = request.getParameter("nickname");
		}
		if (request.getParameter("email") != null)
		{
			email = request.getParameter("email");
		}
		if (request.getParameter("number") != null)
		{
			number = request.getParameter("number");
		}
		if (request.getParameter("sex") != null)
		{
			sex = request.getParameter("sex");
		}
		System.out.println("-------------------------------");
		System.out.println("------------------------");
		System.out.println(new String(sex.getBytes("gbk"),"utf-8"));
		System.out.println(new String(sex.getBytes(),"utf-8"));
		System.out.println(new String(sex.getBytes("utf-8"),"utf-8"));
		System.out.println(new String(sex.getBytes("gb2312"),"utf-8"));
		System.out.println(new String(sex.getBytes("iso-8859-1"),"utf-8"));

		/*
		 * // 验证用户名 if (username.equals("")) { check = 0;
		 * result.append("用户名为空,"); } else ifl
		 * (username.matches("[0-9a-zA-Z]{"+username.length()+"}")==false) {
		 * check = 0; result.append("用户名只能含有数字和字母,"); } else if
		 * (username.length() < 6 || username.length() > 9) { check = 0;
		 * result.append("用户名长度不符合大于等于6位且小于10位的要求,"); } else { try { rs =
		 * dataBase.query("SELECT username FROM user where username = '" +
		 * username + "'"); if (rs.next()) { check = 0;
		 * result.append("用户名已存在,"); } else { if (check == 1) {
		 * user.setUsername(username); } } if (rs.isClosed() == false) {
		 * rs.close(); } } catch (SQLException e) { e.printStackTrace(); } } //
		 * 验证密码 if (password.length() == 0) { check = 0;
		 * result.append("密码为不能空,"); } else { if (!password.equals(repassword))
		 * { check = 0; result.append("两次输入密码不一致,"); } else if
		 * (password.length() < 6 || password.length() > 9) { check = 0;
		 * result.append("密码长度不符合大于等于6位且小于10位的要求,"); } else { if
		 * (!password.matches(".*?[0-9].*?")) { check = 0;
		 * result.append("密码未包含数字,"); } if (!password.matches(".*?[a-z].*?")) {
		 * check = 0; result.append("密码未包含小写字母,"); } if
		 * (!password.matches(".*?[A-Z].*?")) { check = 0;
		 * result.append("密码未包含大写字母,"); } if (check == 1) {
		 * user.setPassword(password); } } }
		 * 
		 * // 验证昵称 if (nickname.length() == 0) { user.setNickname(username); }
		 * else if ((nickname.matches(".*?[\u4e00-\u9fa5].*?") ||
		 * nickname.matches(".*?[0-9].*?") || nickname
		 * .matches(".*?[a-zA-Z].*?")) == false) {
		 * System.out.println("错误的昵称为: "+nickname); check = 0;
		 * result.append("昵称只能包含中文数字和字母,"); } else if (nickname.length() > 10) {
		 * check = 0; result.append("昵称不符合最大长度为10的要求,"); } else {
		 * user.setNickname(nickname); }
		 * 
		 * // 验证邮件地址 if (email.length() == 0) { check = 0;
		 * result.append("邮箱地址不能为空,"); } else if (!email.matches(".+?@.+?")) {
		 * check = 0; result.append("邮箱不符合###@###格式,"); } else {
		 * System.out.println("邮箱为 :"+email); try { //rs =
		 * dataBase.query("SELECT FORM user where email = " + email);
		 * PreparedStatement psm = dataBase.getConnection().prepareStatement(
		 * "SELECT email FROM user where email = ?"); psm.setString(1, email);
		 * rs = psm.executeQuery(); if (rs.next()) { check = 0;
		 * result.append("该邮箱已存在,"); } else { user.setEmail(email); } if
		 * (rs.isClosed() == false) { rs.close(); } if(psm.isClosed()==false){
		 * psm.close(); } } catch (SQLException e) { e.printStackTrace(); } }
		 * 
		 * // 验证手机号码 if (number.length() > 0) { if (!number.matches("\\d{11}"))
		 * { check = 0; result.append("手机号码不符合11位数字要求,"); } else {
		 * user.setNumber(number); }
		 * 
		 * }
		 * 
		 * // 验证性别 if (sex.equals("未知")) { user.setSex(sex); } else if
		 * (sex.equals("男")) { user.setSex(sex); } else if (sex.equals("女")) {
		 * user.setSex(sex); } else { check = 0; result.append("性别不符合要求"); }
		 */
		CheckRegister checkRegister = new CheckRegister();
		ReturnResult returnResult;
		returnResult = checkRegister.checkUsername(username);
		switch (returnResult.getCheck())
		{
		case 1:
			user.setUsername(username);
			break;
		case 0:
			check = 0;
			result.append(returnResult.getStr());
			break;
		default:
			break;
		}
		
		returnResult = checkRegister.checkPassword(password, repassword);
		switch (returnResult.getCheck())
		{
		case 1:
			user.setPassword(password);
			break;
		case 0:
			check = 0;
			result.append(returnResult.getStr());
			break;
		default:
			break;
		}
		
		returnResult = checkRegister.checkNickname(nickname);
		switch (returnResult.getCheck())
		{
		case 1:
			user.setNickname(nickname);
			break;
		case 0:
			check = 0;
			result.append(returnResult.getStr());
			break;
		case 2:
			user.setNickname(username);
		default:
			break;
		}
		
		returnResult = checkRegister.checkEmail(email);
		switch (returnResult.getCheck())
		{
		case 1:
			user.setEmail(email);
			break;
		case 0:
			check = 0;
			result.append(returnResult.getStr());
			break;
		default:
			break;
		}
		
		returnResult = checkRegister.checkNumber(number);
		switch (returnResult.getCheck())
		{
		case 1:
			user.setNumber(number);
			break;
		case 0:
			check = 0;
			result.append(returnResult.getStr());
			break;
		default:
			break;
		}
		
		returnResult = checkRegister.checkSex(sex);
		switch (returnResult.getCheck())
		{
		case 1:
			user.setSex(sex);
			break;
		case 0:
			check = 0;
			result.append(returnResult.getStr());
			break;
		default:
			break;
		}
		

		// 根据结果跳转
		if (check == 1)
		{
			int count = 0;
			try
			{
				count = user.addUser();
			} catch (SQLException e)
			{
				e.printStackTrace();
			}
			if (count == 1)
			{
				//session.setAttribute("user", user);
				Enumeration<String> names = session.getAttributeNames();
				while(names.hasMoreElements()){
					session.removeAttribute(names.nextElement());
				}				
				response.sendRedirect("successRegister.jsp");
			} else
			{
				PrintWriter pw = response.getWriter();
				pw.write("<script>alert('error');</script>");
				pw.close();
				response.sendRedirect("register.jsp");
			}
		} else
		{
			session.setAttribute("user", user);
			session.setAttribute(
					"registerError",
					result.toString().substring(0,
							result.toString().length() - 1));
			response.sendRedirect("errorRegister.jsp");
		}
		dataBase.closeService();

	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException
	{
		// Put your code here
	}

}
